//
//  SecondViewController.swift
//  puretennis
//
//  Created by IYE Technologies on 11/9/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class FriendsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var friendsLoaded = false

    var friendListView: UITableView = UITableView()

    var friendList: [NSMutableDictionary] = []
    
    var friendRequestsList: [NSMutableDictionary] = []
    
    var friendDetailsViewController = UserDetailsViewController()
    
    var searchFriendViewController = SearchFriendViewController()
    
    var friendRequestsViewController = FriendRequestsViewController()


    override func viewDidLoad() {
        ViewUtils.addBackgroundView(self);
        self.navigationItem.titleView = ViewUtils.titleView("我的好友")
        var navigationBarHeight = (self.navigationController?.navigationBar.frame.height)! + ViewUtils.statusBarHeight();
        
        friendListView.separatorStyle = UITableViewCellSeparatorStyle.None
        friendListView.backgroundColor = UIColor.clearColor()
        friendListView.delegate = self
        friendListView.dataSource = self
        
        var margin:CGFloat = 5;
        friendListView.frame.origin = CGPoint(x: margin, y: (navigationBarHeight*1.1));
        var listViewHeight = self.view.frame.height - friendListView.frame.origin.y - (self.tabBarHeight()!)
        friendListView.frame.size = CGSize(width: self.view.frame.size.width - margin * 2, height: listViewHeight);
        
        self.view.addSubview(friendListView);
        
        self.initNavigation();
    }
    
    
    
    func initNavigation(){
        var backButton = UIButton();
        backButton.setImage(UIImage(named: "back"), forState: UIControlState.Normal);
        backButton.showsTouchWhenHighlighted = true;
        backButton.sizeToFit();
        backButton.addTarget(self, action: Selector("back:"), forControlEvents: UIControlEvents.TouchUpInside);
        var backBarButton = UIBarButtonItem(customView: backButton);
        self.navigationItem.leftBarButtonItem = backBarButton;
    }
    
    func back(sender:UIButton){
        self.navigationController?.popViewControllerAnimated(true);
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return friendList.count + friendRequestsList.count;
    }

    func isRequest(index: Int) -> Bool{
        var requestAmount = self.friendRequestsList.count
        return requestAmount > 0 && index <= requestAmount - 1
    }
    
    func userGuid(index:  Int) -> String{
        var requestOrFriendObj = self.requestOrFriend(index) as NSDictionary
        
        if(self.isRequest(index)){
            var sender = requestOrFriendObj.objectForKey("sender") as NSMutableDictionary
            return (sender.objectForKey("guid")) as String
        }else{
            return (requestOrFriendObj.objectForKey("guid")) as String
        }
    }
    
    func requestOrFriend(index: Int) -> AnyObject{
        
        if(self.isRequest(index)){
            return self.friendRequestsList[index] as NSDictionary
        }else{
            return self.friendList[index - self.friendRequestsList.count] as NSDictionary
        }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        
        var index = indexPath.row


        friendDetailsViewController.guid = self.userGuid(index)
        
        friendDetailsViewController.loadUserDetails()
        self.navigationController?.pushViewController(self.friendDetailsViewController, animated: true)                        
        
    }
    
    

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        var index = indexPath.row
        var name: String = ""
        var userGuid: String = ""
        var arrowName: String = "right_arrow_mini"
        var unreadMessageAmout:Int = 0
        var requestOrFriendObj = self.requestOrFriend(index) as NSDictionary
        
        if(self.isRequest(index)){
            var sender = requestOrFriendObj.objectForKey("sender") as NSMutableDictionary
            name = (sender.objectForKey("nickname")) as String
            userGuid = (sender.objectForKey("guid")) as String
            arrowName = "question"
            
        }else{
            var guid = requestOrFriendObj.objectForKey("guid") as String
            name = (requestOrFriendObj.objectForKey("name")) as String;
            userGuid = (requestOrFriendObj.objectForKey("guid")) as String
            unreadMessageAmout = (requestOrFriendObj.objectForKey("unreadMessageAmount")) as Int
        }
        
        
        if(unreadMessageAmout > 0){
            arrowName = "badge_bg"
        }
        
        var cell = PersonalCell();
        cell.setWidth(tableView.frame.width);
        cell.setArrow(arrowName);
        cell.setAvatarImage(ImageUtils.retrieveUserImage(userGuid))
        
        var isCurrentUser = Utils.isCurrentUser(userGuid);
        if(isCurrentUser){
            name = "我";
        }
        cell.setName(name);
        return cell;
    }

    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool{
        return true;
    }

    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

        var index = indexPath.row
        let deleteRequestAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "",handler:deleteFriendRequest);
        
        var deleteImage = UIImage(named: "close_in_row")
        
        deleteRequestAction.backgroundColor = UIColor(patternImage: deleteImage!)
        
        if(self.isRequest(index)){
            
            let acceptRequestAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "",handler:acceptFriendRequest);
            
            var acceptImage = UIImage(named: "ok_in_row")
            
            acceptRequestAction.backgroundColor = UIColor(patternImage: acceptImage!)

            
            return [deleteRequestAction, acceptRequestAction];
            
        }else{
            
            return [deleteRequestAction];
        }
    }

    func deleteFriendRequest(tableViewRowAction:UITableViewRowAction!,indexPath:NSIndexPath!){
        ConfirmView(message: "确定删除此小伙伴?", confirm: { () -> Void in
            var index = indexPath.row
            var guid = self.userGuid(index)
            if(self.isRequest(index)){
                self.friendRequestsList.removeAtIndex(index);
            }else{
                self.friendList.removeAtIndex(index - self.friendRequestsList.count);
            }
            self.friendListView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            self.deleteFriend(guid);
            }, cancel: nil).show();
    }
    
    func acceptFriendRequest(tableViewRowAction:UITableViewRowAction!,indexPath:NSIndexPath!){
        var index = indexPath.row
        var guid = self.userGuid(index)
        self.friendRequestsList.removeAtIndex(index);
        self.acceptFriend(guid)
    }

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){

    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated);
        self.friendDetailsViewController = UserDetailsViewController()
        GlobalVariables.friendViewController = self
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        self.initNavigationBar();
        self.loadFriends();
        self.showTabBar();
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        GlobalVariables.friendViewController = nil
    }

    func acceptFriend(guid: String){
        var url = "/api/v1/friends/request/accept/" + guid;
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var newFriend = response as NSMutableDictionary
            self.friendList.append(newFriend)
            self.friendListView.reloadData()
            
            }, errorHandle: { (error) -> Void in

        })
    }
    
    func deleteFriend(guid: String){
        var url = "/api/v1/friends/delete/" + guid;
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            }, errorHandle: { (error) -> Void in
        });
    }
    
    func initNavigationBar(){
        let searchFriendButton = UIButton();
        searchFriendButton.setImage(UIImage(named: "add"), forState: UIControlState.Normal);
        searchFriendButton.contentMode = UIViewContentMode.Right;
        searchFriendButton.showsTouchWhenHighlighted = true;
        searchFriendButton.sizeToFit();
        searchFriendButton.addTarget(self, action: Selector("searchFriendView:"), forControlEvents: UIControlEvents.TouchUpInside);
        let searchFriendItem = UIBarButtonItem(customView: searchFriendButton);
        self.navigationItem.rightBarButtonItems = [searchFriendItem];
        
    }
    
    func searchFriendView(barButtonItem: UIBarButtonItem){
        self.navigationController?.pushViewController(self.searchFriendViewController, animated: true)
    }

    func loadFriends(){
        self.processing();
        self.friendsLoaded = true;

        let url = "/api/v1/friends";

        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var friends: NSMutableDictionary = response as NSMutableDictionary
            self.friendList = friends.objectForKey("friends") as [NSMutableDictionary]
            self.friendRequestsList = friends.objectForKey("requests") as [NSMutableDictionary]
            self.friendListView.reloadData()
            self.processComplete();
        }, errorHandle: { (error) -> Void in
            self.processComplete();
        });
    }
    
    func friendRequests(button: UIButton){
        friendRequestsViewController.friendsViewController = self
        friendRequestsViewController.loadFriendRequests()
        self.navigationController?.pushViewController(friendRequestsViewController, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        Utils.debug("Memory warning")

    }
}

